package org.example.service;

import org.apache.commons.lang.StringUtils;
import org.example.internalCommon.constant.CommonStatusEnum;
import org.example.internalCommon.constant.IdentityConstants;
import org.example.internalCommon.constant.TokenConstants;
import org.example.internalCommon.dto.ResponseResult;
import org.example.internalCommon.dto.TokenResult;
import org.example.internalCommon.response.TokenResponse;
import org.example.internalCommon.util.JwtUtils;
import org.example.internalCommon.util.RedisprefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshTokenSrc){
        // 解析token
        TokenResult tokenResult = JwtUtils.checkToken(refreshTokenSrc);
        if (tokenResult == null) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode()
                    , CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
//        读取redis的refreshToken
        String refreshTokenKey = RedisprefixUtils.generatorTokenKey(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);
//        校验token
        if ((StringUtils.isBlank(refreshTokenRedis)) || (!refreshTokenSrc.trim().equals(refreshTokenRedis.trim()))) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode()
                    , CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }
//        生成双token
        String accessToken = JwtUtils.generatorToken(phone, IdentityConstants.PASSENGER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);

        String accessTokenKey = RedisprefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);


        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 5, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 200, TimeUnit.SECONDS);

        // 响应
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }
}
